//
//  Untitled 2.swift
//  PLDownload
//
//  Created by bin hu on 2025/7/7.
//

import Foundation

struct EncryptedM3U8 {
    let tsSegments: [URL]
    let keyURI: String?
    let iv: Data?
    let method: String?  // "AES-128"等
}

/// 加密m3u8解析器
class M3U8Parser {
    func parseEncryptedM3U8(content: String, baseURL: URL) -> EncryptedM3U8 {
        var segments: [URL] = []
        var keyURI: String?
        var iv: Data?
        var method: String?
        
        let lines = content.split(separator: "\n")
        for line in lines {
            let trimmedLine = line.trimmingCharacters(in: .whitespaces)
            
            if trimmedLine.hasPrefix("#EXT-X-KEY") {
                let attributes = parseAttributes(line: String(trimmedLine))
                method = attributes["METHOD"]
                keyURI = attributes["URI"]?.replacingOccurrences(of: "\"", with: "")
                if let ivHex = attributes["IV"]?.replacingOccurrences(of: "0x", with: "") {
                    iv = Data(hexString: ivHex)
                }
            }
            else if !trimmedLine.hasPrefix("#") && !trimmedLine.isEmpty {
                if let segmentURL = URL(string: trimmedLine, relativeTo: baseURL) {
                    segments.append(segmentURL)
                }
            }
        }
        
        return EncryptedM3U8(
            tsSegments: segments,
            keyURI: keyURI,
            iv: iv,
            method: method
        )
    }
    
    private func parseAttributes(line: String) -> [String: String] {
        var attributes = [String: String]()
        let pattern = "([A-Z-]+)=(\"([^\"]+)\"|([^,]+))"
        
        do {
            let regex = try NSRegularExpression(pattern: pattern)
            let matches = regex.matches(in: line, range: NSRange(line.startIndex..., in: line))
            
            for match in matches {
                guard let keyRange = Range(match.range(at: 1), in: line),
                      let valueRange = Range(match.range(at: 2), in: line) else {
                    continue
                }
                
                let key = String(line[keyRange])
                var value = String(line[valueRange])
                
                if value.hasPrefix("\"") && value.hasSuffix("\"") {
                    value = String(value.dropFirst().dropLast())
                }
                
                attributes[key] = value
            }
        } catch {
            print("Attribute parsing error: \(error)")
        }
        
        return attributes
    }
}

